'''
Created on Sep 6, 2012

@author: thomas_dao
'''
from web import base
from web.base import BaseHandler
from web import urls
from kid import util
import json
import logging
from google.appengine.ext import ndb
from app import article_async, board_async, note_async
from kid import jinja_lib
from google.appengine.ext.ndb import Cursor


class BoardPageHandler(BaseHandler):
    @ndb.synctasklet
    def get(self):
        next_curs = self.request.get('curs')
        start_curs = None
        logging.info('next start_curs' + next_curs)
        if next_curs is not None and next_curs is not "":
            start_curs = Cursor(urlsafe=next_curs)

        
        env = jinja_lib.jinja_environment()
        template = env.get_template('board-page.html')
        user_key = util.get_current_user_key()
        user = None
        values = {}
        if user_key:
            (user, user_boards) = yield (user_key.get_async(), 
                                   board_async.get_boards_followed_by_user(user_key))
            values['boards_of_user'] = json.dumps(util.ndb_to_list(user_boards))
            values['user'] = util.ndb_to_dict(user)
            values['user_json'] = json.dumps(values['user'])
        
        
        (boards, cur, more) = yield board_async.get_top_follow(start_cursor=start_curs)
        values['boards'] = yield util.ndb_to_list_async(boards, detail=['user'])
        if cur:
            values['cursor'] = cur.urlsafe()
        values['more'] = more
        
        # Fetch article belong to the boards
        board_keys = [x.key for x in boards]
        notes = yield note_async.get_by_boards(board_keys, limit=3)
        if notes:            
            notes = yield util.ndb_to_list_async(notes, detail=['article'])            
            for board in values['boards']:
                board['articles'] = [x['article'] for x in notes if x['board']==board['id']]
        
        self.response.out.write(template.render(values))
        
app = urls.app

def main():
    app.run()

if __name__ == '__main__':
    main()